import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'view_model/af_create_post_view_model.dart';

class AfCreatePostScreen extends ConsumerStatefulWidget {
  const AfCreatePostScreen({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfCreatePostScreenState();
}

class _AfCreatePostScreenState extends ConsumerState<AfCreatePostScreen> {
  @override
  Widget build(BuildContext context) {
    final afCreatePostState = ref.watch(afCreatePostServiceProvider);
    final imgCount = afCreatePostState.imgs.length < 3
        ? (afCreatePostState.imgs.length + 1)
        : afCreatePostState.imgs.length;
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).maybePop();
          },
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 20,
              ),
              child: Assets.icons.iconMineBack.image(width: 25),
            ),
          ),
        ),
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: _createPost,
            child: Container(
              decoration: BoxDecoration(
                color: const Color(0xff2A2828),
                borderRadius: BorderRadius.circular(16),
              ),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              margin: const EdgeInsets.only(right: 20),
              child: const Text(
                'Post',
                style: TextStyle(
                  color: Color(0xffffffff),
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          )
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                GridView.custom(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
                  scrollDirection: Axis.vertical,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3, //横轴三个子widget
                      mainAxisSpacing: 14,
                      crossAxisSpacing: 12,
                      childAspectRatio: 104 / 110 //宽高比为1时，子widget
                      ),
                  childrenDelegate: SliverChildBuilderDelegate(
                    (context, position) {
                      if ((position == imgCount - 1) &&
                          (afCreatePostState.imgs.length < 3)) {
                        return ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              _pickImg();
                            },
                            child: AspectRatio(
                              aspectRatio: 104 / 110,
                              child: Container(
                                decoration: BoxDecoration(
                                  color: const Color(0xffF8F8F8),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Center(
                                  child: Assets.icons.createPostAddImg
                                      .image(width: 27),
                                ),
                              ),
                            ),
                          ),
                        );
                      }
                      final imgUrl = afCreatePostState.imgs[position];
                      return ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Stack(
                          children: [
                            AspectRatio(
                              aspectRatio: 104 / 110,
                              child: Image.asset(
                                imgUrl,
                                fit: BoxFit.cover,
                              ),
                            ),
                            Positioned(
                              top: 0,
                              right: 0,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  ref
                                      .read(
                                          afCreatePostServiceProvider.notifier)
                                      .removeImgUrl(imgUrl);
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: const Color(0xff000000)
                                        .withOpacity(0.3),
                                    borderRadius: const BorderRadius.only(
                                      bottomLeft: Radius.circular(8),
                                    ),
                                  ),
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 6,
                                    vertical: 4,
                                  ),
                                  child: Assets.icons.iconDelete.svg(
                                    width: 12,
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      );
                    },
                    childCount: imgCount,
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: TextField(
                    onChanged: (value) {
                      ref
                          .read(afCreatePostServiceProvider.notifier)
                          .updateTitle(value);
                    },
                    decoration: InputDecoration(
                      hintText: "Type your title.",
                      hintStyle: TextStyle(
                        color: const Color(0xff000000).withOpacity(0.5),
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                      fillColor: const Color(0xffF8F8F8),
                      border: InputBorder.none,
                      filled: true,
                    ),
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Container(
                    decoration: BoxDecoration(
                      color: const Color(0xffF8F8F8),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    padding: const EdgeInsets.only(bottom: 10),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      maxLength: 600,
                      onChanged: (value) {
                        ref
                            .read(afCreatePostServiceProvider.notifier)
                            .updateContent(value);
                      },
                      decoration: InputDecoration(
                        hintText: "Start your creation...",
                        hintStyle: TextStyle(
                          color: const Color(0xff000000).withOpacity(0.5),
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                        fillColor: const Color(0xffF8F8F8),
                        border: InputBorder.none,
                        filled: true,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  _pickImg() async {
    if (!await Permission.photos.isGranted) {
      var permissionStatus = await Permission.photos.request();
      if (permissionStatus != PermissionStatus.granted) {
        "You have not authorised this permission.".toast();
        return;
      }
    }
    var picker = ImagePicker();
    picker.pickImage(source: ImageSource.gallery).then((value) {
      if (value != null) {
        ref.read(afCreatePostServiceProvider.notifier).addImgUrl(value.path);
      }
    });
  }

  _createPost() {
    final item = ref.read(afCreatePostServiceProvider);
    if (item.imgs.isEmpty) {
      return "please select at least one image ".toast();
    }
    if (item.title.isEmpty) {
      return "title is not empty".toast();
    }
    if (item.content.isEmpty) {
      return "content is not empty".toast();
    }
    SmartDialog.showLoading(
      backDismiss: false,
      builder: (_) => const Center(
        child: CircularProgressIndicator(),
      ),
    );
    ref.read(afMyCreatedPostsListServiceProvider.notifier).creatPost(item);
    Future.delayed(const Duration(seconds: 2), () {
      SmartDialog.dismiss();
      "create success".toast(onDismiss: () {
        Navigator.of(context).maybePop();
      });
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfCreatePostScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
